<script setup lang="ts">

import http from '@/http';
import { useUserStore } from '@/stores/user';
import 'element-plus/dist/index.css';
import { ref, watch, watchEffect ,onMounted} from 'vue';
import { useRouter } from 'vue-router';
import { useCookies } from '@vueuse/integrations/useCookies'
const user2=useUserStore();
const getUser=user2.getUserx;
    // 从 cookie
    const cookie=useCookies();
// 存储当前选中的行数据
const selectedRows = ref([]);
onMounted(()=>{
    fetchDictData("his_medicines_type")
    fetchDictData2("his_prescription_type")
})
// 表格的引用
const tableRef = ref(null);
let flg=ref(false)
// 处理表格选择项变化的方法
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
  flg.value = rows.length > 0;
};
//当前页的页号发生改变
const handleCurrentChange = (val: number) => {
  //console.log(`current page: ${val}`)
  //重新获取当前页的数据
  pageNum.value = val
  page()
}
const handleSizeChange = (val: number) => {
  pageSize.value = val;
    page();
};
//获取药品类型
//获取药品类型
let dictLabelData = ref([])
const fetchDictData = async (dictType) => {
  await http.get('/api/dict/data/' + dictType).then((res) => {
    dictLabelData.value = res
  }).catch((error) => {
    console.error('获取字典数据失败:', error);
  })
};
//his_medicines_type
let dictLabel1Data = ref([])
const fetchDictData2 = async (dictType) => {
  await http.get('/api/dict/data/' + dictType).then((res) => {
    dictLabel1Data.value = res
  }).catch((error) => {
    console.error('获取字典数据失败:', error);
  })
};
//随机生成入库订单编号
function generateTimestampRandomCG() {
  const prefix = 'CG1';
  const timestamp = Date.now().toString(); // 获取当前时间戳
  let randomNumbers = '';

  // 生成剩余随机数字
  for (let i = 0; i < 18 - timestamp.length; i++) {
    randomNumbers += Math.floor(Math.random() * 10);
  }

  return prefix + timestamp + randomNumbers;
}


let p=generateTimestampRandomCG()// 输出类似 "CG1698765432101234567"
//获取制单人
const userStore=useUserStore()
const user=userStore.getUserx

//获取药品
//当前页
let pageNum = ref(1)
//每页条数
let pageSize = ref(5)
//总条数
let total = ref(0)
//条件
let medicinesName = ref('')
let keywords = ref('')
let medicinesType = ref('')
let producterName = ref('')
let prescriptionType = ref('')
let status = ref('')
let modData=ref([])
let dialogTableVisible=ref(false)
 function addmod(){
   page()
    dialogTableVisible.value=true
    
 }
function page(){
  http.get("/med/page",{params:{
      pageNum: pageNum.value,
            pageSize: pageSize.value,
            medicinesName: medicinesName.value,
            keywords: keywords.value,
            medicinesType: medicinesType.value,
            producterName: producterName.value,
            prescriptionType: prescriptionType.value,
            status: status.value
    }}).then((res)=>{
        modData.value=res.list
        total.value=res.total
    })
  
}
//重置
function reset(){
  keywords.value=''
   medicinesType.value=''
   prescriptionType.value=''
   page()
}
//失去焦点
function selectkeyword(){
  page()
}
//关闭弹框
function close(){
   keywords.value=''
   medicinesType.value=''
   prescriptionType.value=''
   dialogTableVisible.value=false
}
let zong=ref(0);
let itms=ref([])
//确定
function but(){
      selectedRows.value.forEach(element => {
        const newItem = {
     keywords:element.keywords,     
    conversion: element.conversion,
    purchaseId: p,
    medicinesId: element.medicinesId,
    unum:element.conversion+element.unit,
    producterName: element.producterName,
    purchaseNumber:1, // 默认值为 '1'
    medicinesName: element.medicinesName,
    unit: element.unit,
    tradePrice: element.prescriptionPrice,
    medicinesType: element.medicinesType,
    prescriptionType: element.prescriptionType,
    producterId: element.producterId,
    tradeTotalAmount: parseFloat(element.prescriptionPrice) * 1, // 计算 batchAmount
    batchNumber: '',
    remark: ''
  };
  for (let index = 0; index < itms.value.length; index++) {
    if(itms.value[index].medicinesId==element.medicinesId){
      itms.value[index].purchaseNumber+=1
      itms.value[index].tradeTotalAmount=itms.value[index].purchaseNumber*itms.value[index].tradePrice
      return
    }     
  }
   itms.value.push(newItem); // 将新对象添加到数组中   
  })
  //console.log(itms.value)
 dialogTableVisible.value=false 
}
//删除
 function bouton(r){
       itms.value.forEach(e => {
        if(e.medicinesId==r){
          // 找到要移除的对象的索引
const indexToRemove = itms.value.findIndex(e => e.medicinesId ===r );
// 如果找到对象，则移除
if (indexToRemove !== -1) {
  itms.value.splice(indexToRemove, 1);
}
        }
       });
 }
 //数量改变
 function sq(data){
    itms.value.forEach(element => {
      if(element.medicinesId===data.medicinesId){
        element.tradeTotalAmount=data.purchaseNumber*data.tradePrice
      }
    });
}
//批次号改变
//监听
const stopWtach = watchEffect(() => {
         if(itms.value.length!=null){
          zong.value=0
          itms.value.forEach(element => {
              zong.value+=element.tradeTotalAmount;          
          });
    
         }
         parseFloat(zong.value.toFixed(2))
 })
 let proData=ref([])
//获取供应商
http.get('/pro/getAll').then(res=>{
  proData.value=res
})
//添加
let purchase=ref({
    purchaseId:p,
    createBy:getUser.userName,
    providerId:'',
    createTime:'',
    purchaseTradeTotalAmount: zong
})
//批量设置
let dialogVisible1 = ref(false)
//批量对象
let formData = ref({
   num:0,
  price:0,
  batch:'',
  remark:''
})


function resent(){
  dialogVisible1.value=true
}
//批发确定
function but1(){
   itms.value.forEach(element => {
    element.tradePrice=formData.value.price
    element.purchaseNumber=formData.value.num
    element.batchNumber=formData.value.batch
    element.remark=formData.value.remark
    element.tradeTotalAmount=formData.value.num*formData.value.price
  });
  dialogVisible1.value=false
  formData.value.num=0
  formData.value.price=0
  formData.value.batch=''
  formData.value.remark=''
}
function handleDialogClose(){
  formData.value.num=0
  formData.value.price=0
  formData.value.batch=''
  formData.value.remark=''
}
function kk(){
  dialogVisible1.value=false
  formData.value.num=0
  formData.value.price=0
  formData.value.batch=''
  formData.value.remark=''

}
const router=useRouter();//返回
//暂缓确定
const data = {
  purchase: purchase.value,
  stockPurchaseItem: itms.value
};
function stop(){
 add()
 router.push('/stock/purchase')
}

function  add(){
   http.post('/pur/insert',data,{
  headers: {
    'Content-Type': 'application/json'
  } }).then((res)=>{
     
  })
}
//提交确定
function update(){
http.post('/pur/update',purchase.value).then((res)=>{
      
})
}
function submit(){
  add()
  update()
  router.push('/stock/purchase')
}
</script>



<template>
     <el-row justify="end">
          <el-col :span="2.5">
            <div class="grid-content ep-bg-purple-light" >
              <el-button type="primary" icon="Plus" @click="addmod" width="100px">添加药品</el-button>
              </div>
          </el-col>
          <el-col :span="2.5">
            <div class="grid-content ep-bg-purple-light" >
              <el-button  icon="Operation" @click="resent" width="100px" type="success">批量设置</el-button>
             </div>
          </el-col>
          <el-col :span="2.5">
            <div class="grid-content ep-bg-purple-light" >
              <el-button  icon="Check" @click="stop" width="100px" type="warning">暂缓</el-button>
             </div>
          </el-col>
          <el-col :span="2.5">
            <div class="grid-content ep-bg-purple-light" >
              <el-button  icon="Finished" @click="submit" width="100px" type="danger">提交审核</el-button>
             </div>
          </el-col>
        </el-row>
  <el-row>
      <el-col :span="6">
        单据号    <el-input v-model="purchase.purchaseId" placeholder="单据号" disabled  style="width: 220px;"></el-input>
      </el-col>
      <el-col :span="5" >
        制单人  <el-input v-model="purchase.createBy" placeholder="制单人" disabled style="width: 150px;"></el-input>
      </el-col>
      <el-col :span="5">
          供应商
          <el-select v-model="purchase.providerId" placeholder="请选择" style="width: 150px;">
            <el-option
              v-for="item in proData"
              :label="item.providerName"
              :value="item.providerId"
              :key="item.providerId">
            </el-option>
          </el-select>
      </el-col>
      <el-col :span="5" >
        制单时间  <el-input v-model="purchase.createTime" type="Date" placeholder="制单时间" style="width: 150px;"></el-input>
      </el-col>
  </el-row>
  <el-row>
    <el-col>
        总批发额    <el-input v-model="purchase.purchaseTradeTotalAmount" disabled placeholder="总批发额" style="width: 200px;"></el-input> 
    </el-col>
  </el-row>
      <el-table :data="itms" style="width: 100%" border>
        <el-table-column prop="medicinesId" label="药品ID" width="80"></el-table-column>
        <el-table-column prop="medicinesName" label="药品名称" width="150"></el-table-column>
        <el-table-column prop="unum" label="规格"  width="120"></el-table-column>
        <el-table-column prop="producterName" label="生产厂家" width="220"></el-table-column>
        <el-table-column  label="数量" width="100">
          <template #default="scope">
              <el-input v-model="scope.row.purchaseNumber" @blur="sq(scope.row)"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="unit" label="单位" width="100"></el-table-column>
        <el-table-column prop="tradePrice" label="批次价" width="100"></el-table-column>
        <el-table-column prop="tradeTotalAmount" label="批次额" width="100"></el-table-column>
        <el-table-column  label="批次号" width="120">
          <template #default="scope">
              <el-input v-model="scope.row.batchNumber" ></el-input>
          </template>
        </el-table-column>
        <el-table-column  label="备注" width="150">
          <template #default="scope">
              <el-input v-model="scope.row.remark"></el-input>
          </template>
        </el-table-column>
        <el-table-column  label="操作" width="120">
          <template #default="scope">
              <el-button type="danger" icon="Delete"  @click="bouton(scope.row.medicinesId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="dialogTableVisible"  width="1200" title="添加药品" center @close="close">
        <el-row>
          <el-col :span="5">
          <div class="grid-content ep-bg-purple" >
        关键字    <el-input v-model="keywords" @blur="selectkeyword" placeholder="请输入关键字" style="width: 120px;"></el-input>
        </div>
        </el-col>
        <el-col :span="7">
          <div class="grid-content ep-bg-purple" >
        药品类型   
          <el-select v-model="medicinesType" @blur="selectkeyword"  placeholder="请选择" style="width: 200px;">
            <el-option
              v-for="item in dictLabelData"
              :label="item.dict_label"
                    :value="item.dict_value"
                    :key="item.dict_value">
            </el-option>
          </el-select>
        
        </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content ep-bg-purple" >
        处方类型  
          <el-select v-model="prescriptionType" @blur="selectkeyword"  placeholder="请选择" style="width: 100px;">
            <el-option
              v-for="dict in dictLabel1Data"
              :label="dict.dict_label"
              :value="dict.dict_value"
              :key="dict.dict_value">
            </el-option>
          </el-select>
       
        </div>
        </el-col>
        <el-col :span="5">
          <div class="grid-content ep-bg-purple" >
            <el-button  icon="Refresh" @click="reset" width="100px">重置</el-button>
        </div>
        </el-col>
        </el-row>
        <el-table :data="modData" style="width: 100%;margin-top: 20px;" row-key="medicinesId" border @selection-change="handleSelectionChange" ref="tableRef">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
            <el-table-column prop="medicinesId" label="药品id" align="center"  width="80"></el-table-column>
            <el-table-column prop="medicinesName" label="药品名称" align="center" width="200"></el-table-column>
            <el-table-column prop="medicinesNumber" label="药品编码" align="center" width="120"></el-table-column>
            <el-table-column prop="producterName" label="生产厂家" align="center" width="230"></el-table-column>
            <el-table-column prop="dictLabel" label="药品类型" align="center"width="130" ></el-table-column>
            <el-table-column prop="dictLabel1" label="处方类型" align="center" width="130"></el-table-column>
            <el-table-column prop="keywords" label="关键字" align="center"></el-table-column>
            </el-table>
            <!--分页-->
  <el-row style="margin-top: 20px;">
    <el-col :span="12" :offset="6">
      <div class="demo-pagination-block">
         <el-pagination
        @size-change="handleSizeChange"
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[2, 5, 8, 10]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @current-change="handleCurrentChange"
    />
      </div>
    </el-col>
  </el-row> 
       <el-row type="flex" justify="center" >
         <el-col span="">
          <el-button   @click="but" :disabled="!flg">确定</el-button>
           <el-button   @click="close">关闭</el-button>
         </el-col>
     </el-row>
  </el-dialog>
  <el-dialog title="批量设置" v-model="dialogVisible1" width="400px" @close="handleDialogClose" center>
     <el-from :model="formData" label-width="100px" >
    <el-form-item label="数量">
      <el-input v-model="formData.num" placeholder="请输入数量" type="number"></el-input>
    </el-form-item>
    <el-form-item label="批发价格">
      <el-input v-model="formData.price"  type="number"></el-input>
    </el-form-item>
    <el-form-item label="批发号">
           <el-input v-model="formData.batch" placeholder="请输入批发号" ></el-input>
    </el-form-item>
    <el-form-item label="备注">
       <el-input v-model="formData.remark" placeholder="请输入备注"></el-input>
    </el-form-item>
     </el-from>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="kk">取 消</el-button>
        <el-button type="primary" @click="but1">确 定</el-button>
      </span>
    </template>
  </el-dialog>
  </template>
 
<style scoped>
h1, h2 {
  margin-bottom: 20px;
}

.el-button {
  margin-right: 10px;
}
</style>